package com.promise.jokerdream.work.penguin

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.pc.QueryFightTowerResponse
import com.promise.jokerdream.response.pc.QueryPenguinShareResponse
import com.promise.jokerdream.response.pc.SimplePCResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import kotlinx.coroutines.delay

/**
 * 斗神塔工作
 */
class FightTowerWork(
    private val userId: String,
    private val autoShare: Boolean = false
) : BaseWork(userId) {

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override val name: String
        get() = "斗神塔"

    override val priority: Int
        get() = 3

    // 存储等待时间
    private var waitTimeSeconds: Int = 0
    
    // 记录分享是否已达到上限
    private var shareLimitReached: Boolean = false

    override suspend fun executeWork(): WorkResult {
        return try {
            var challengeCount = 0
            val maxChallenges = 500

            while (challengeCount < maxChallenges) {
                // 查询斗神塔信息
                val queryResult = gameApi.queryFightTower()
                val shouldContinue = queryResult.foldWithApiException(
                    onSuccess = { towerInfo ->
                        when (towerInfo.status) {
                            0 -> {
                                // 未开始，直接挑战
                                val fightResult = gameApi.fightTower()
                                fightResult.foldWithApiException(
                                    onSuccess = { response ->
                                        challengeCount++
                                    },
                                    onFailure = { code, msg ->
                                        historyManager.addHistory(name, msg, code)
                                    }
                                )
                                true
                            }
                            1 -> {
                                // 检查是否需要分享
                                if (autoShare && !shareLimitReached && shouldShare(towerInfo)) {
                                    handleShare()
                                }
                                
                                // 进行中，检查剩余时间
                                if (towerInfo.leftFightTime > 0) {
                                    waitTimeSeconds = towerInfo.leftFightTime
                                    delay(waitTimeSeconds * 1000L)
                                }
                                
                                // 执行挑战
                                val fightResult = gameApi.fightTower()
                                fightResult.foldWithApiException(
                                    onSuccess = { response ->
                                        challengeCount++
                                    },
                                    onFailure = { code, msg ->
                                        historyManager.addHistory(name, msg, code)
                                    }
                                )
                                true
                            }
                            2 -> {
                                // 战败，不自动复活，直接结束
                                false
                            }
                            3 -> {
                                // 结束战斗，检查是否需要分享
                                if (autoShare && !shareLimitReached && shouldShare(towerInfo)) {
                                    handleShare()
                                }
                                false
                            }
                            else -> {
                                false
                            }
                        }
                    },
                    onFailure = { code, msg ->
                        historyManager.addHistory(name, msg, code)
                        false
                    }
                )
                
                if (!shouldContinue) {
                    break
                }
                delay(300)
            }

            WorkResult.Success

        } catch (e: kotlinx.coroutines.CancellationException) {
            // 协程被取消，这是正常情况
            WorkResult.Failure(e, "任务被取消")
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }

    /**
     * 处理分享
     */
    private suspend fun handleShare() {
        if (shareLimitReached) return
        
        val queryResult = gameApi.queryPenguinShare()
        queryResult.foldWithApiException(
            onSuccess = { shareInfo ->
                if (isMaxShareReached(shareInfo)) {
                    // 达到上限，设置标志并执行自动挑战
                    shareLimitReached = true
                    val autoResult = gameApi.autoFightTower()
                    autoResult.foldWithApiException(
                        onSuccess = { response ->
                            historyManager.addHistory(name, response.msg)
                        },
                        onFailure = { code, msg ->
                            historyManager.addHistory(name, msg, code)
                        }
                    )
                } else {
                    val shareResult = gameApi.shareGame(4)
                    shareResult.foldWithApiException(
                        onSuccess = { response ->
                            historyManager.addHistory(name, response.msg)
                        },
                        onFailure = { code, msg ->
                            historyManager.addHistory(name, msg, code)
                        }
                    )
                }
            },
            onFailure = { code, msg ->
                historyManager.addHistory(name, msg, code)
            }
        )
    }

    /**
     * 判断是否应该分享
     */
    private fun shouldShare(response: QueryFightTowerResponse): Boolean {
        return response.curLayer > 10 && response.curLayer % 10 == 1
    }

    /**
     * 检查是否可以分享斗神塔
     */
    private fun canShareFightTower(shareInfo: QueryPenguinShareResponse): Boolean {
        val fightTowerShare = shareInfo.shareInfos.find { it.shareType == 4 }
        return fightTowerShare?.canShare == 1
    }

    /**
     * 检查是否已达到最大分享次数
     */
    private fun isMaxShareReached(shareInfo: QueryPenguinShareResponse): Boolean {
        return shareInfo.dayShareTimes >= shareInfo.dayMaxShareTimes
    }
}